<template>
	<view>
		<view class="box">
			<image class="bg" :src="imgUrl" />
			<view class="shader"></view>
		</view>
		<view>
			<scroll-view scroll-y="true">
				<view class="other">
					<text class="title">{{songname||'当前无音乐'}}</text>
					<text class="artist">{{artist}}</text>
					<image class="album" mode="widthFix" :style="{transform:`rotate(${0.25*rotateAngle}deg)`}"
						:src="imgUrl" />
					<view class="lyrics">
						<view class="lyricsWrap" :style="{ transform : 'translateY(' + -(currentIndex-2)*6 + 'vh)' }">
							<text class="lyricsItem" :class="{ active : currentIndex-1 == index }"
								v-for="(lrc,index) in lyrics" :key="index">{{lrc.lyric}}</text>
						</view>
					</view>
					<view class="progressBar">
						<text>{{secToTime(nowTime)}}</text>
						<slider style="width: 50%;" :max="bgm.duration" :value="nowTime" @change="changeTime"></slider>
						<text>{{secToTime(bgm.duration)}}</text>
					</view>
					<view class="footer">
						<image style="width: 11vw;height: 11vw;" :src="playModeUrl()" @click="changePlayMode" />
						<image src="@/static/arrow-left.png"></image>
						<image @click="playMusic" :src="isPlay?'/static/playWhite.png':'/static/pause.png'"></image>
						<image src="@/static/arrow-right.png" @click="nextSong"></image>
						<image style="width: 9vw;height: 9vw;" src="@/static/24gl-playlistMusic4.png"
							@click="playListShow" />
					</view>
				</view>
			</scroll-view>
			<view :style="showPlayList?{right:'0vw',opacity:1}:{right:'-100vw',opacity:0}" class="playList">
				<text style="font-size: 5vh;">播放队列</text>
				<text style="line-height: 4vh;color: #999;font-size: 0.8em;">共{{listLength()}}首歌曲</text>
				<scroll-view class="scv" scroll-y="true" enable-flex="true">
					<view class="listItem" v-for="(listItem,index) in songList" :key="listItem.id"
						:class="{listActive:listCurrent()==index}">
						<view class="listText">
							<text class="listTitle">{{listItem.name}}</text>
							<text class="listArtist">{{listItem.artist}}</text>
						</view>
						<uni-icons color="#fff" type="right"></uni-icons>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onUnload,
		onBackPress
	} from "@dcloudio/uni-app"
	import {
		getCurrentInstance,
		onMounted,
		onUnmounted,
		reactive,
		ref
	} from "vue";
	import baseUrl from '@/config.js'
	let id = ref(0)
	let imgUrl = ref("")
	let songname = ref("")
	let isPlay = ref(false)
	const bgm = uni.getBackgroundAudioManager()
	let lyrics = reactive([])
	let playMode = ref(getApp().globalData.playMode)
	let songList = reactive([])
	let artist = ref("")

	bgm.onEnded((result) => {
		if (playMode.value === 2) bgm.seek(0)
		else nextSong()
	})
	
	onLoad((option)=>{
		init()
	})

	function init() {
		// console.log(getApp().globalData.playList,getApp().globalData.currentPlayIndex,getApp().globalData.playList[getApp().globalData.currentPlayIndex])
		if (getApp().globalData.playList[getApp().globalData.currentPlayIndex] === undefined) return
		currentIndex.value = 0
		for (let i = 0; i < songList.length; i++) songList.pop()
		songList.push(...getApp().globalData.playList)
		// console.log(songList)
		id = getApp().globalData.playList[getApp().globalData.currentPlayIndex].id
		uni.request({
			url: baseUrl + "/song/url/v1",
			data: {
				id: id,
				level: 'lossless'
			},
			success(res1) {
				// console.log(res1)
				bgm.title = "test"
				bgm.src = res1.data.data[0].url
				listenLyricIndex()
				listenSlider()
				uni.request({
					url: baseUrl + '/song/detail',
					data: {
						ids: id
					},
					success(res2) {
						bgm.title = res2.data.songs[0].name
						songname.value = res2.data.songs[0].name
						imgUrl.value = res2.data.songs[0].al.picUrl
						let artistStr = ""
						let v = res2.data.songs[0].ar
						let l = v.length
						if (l === 1) artistStr = v[0].name
						else {
							for (let c = 0; c < l; c++) {
								artistStr += c == l - 1 ? artistStr + ',' : artistStr
							}
						}
						artist.value = artistStr
						// console.log(res2)
						uni.request({
							url: baseUrl + `/lyric`,
							data: {
								id: id
							},
							success(res3) {
								let l = lyrics.length
								for (let c = 0; c < l; c++) {
									lyrics.pop()
								}
								// console.log(res3)
								let t = res3.data.lrc.lyric.split("\n")
								// console.log(t)
								t.forEach((value) => {
									let i = value.indexOf(']')
									let timeStr = value.slice(1, i)
									let time = 0
									if (timeStr == "") {
										time = 99999999
									} else {
										let timeArray = timeStr.split(':')
										if (timeArray.length == 3) {
											time += parseInt(timeArray[0]) * 3600
											time += parseInt(timeArray[1]) * 60
											time += parseFloat(timeArray[2])
										} else {
											time += parseInt(timeArray[0]) * 60
											time += parseFloat(timeArray[1])
										}
									}
									let str = value.slice(i + 1, value.length)
									lyrics.push({
										time: time,
										lyric: str
									})
								})
								// console.log(lyrics)
							}
						})
					}
				})
			}
		})
	}

	let timerCount = []
	let nowTime = ref(0)
	let rotateAngle = ref(0)

	function playMusic() {
		if (bgm.paused) {
			bgm.play()
			listenLyricIndex()
			listenSlider()
		} else {
			bgm.pause()
			timerCount.forEach(item => {
				clearInterval(item)
			})
		}
		isPlay.value = !bgm.paused
	}

	let currentIndex = ref(0)
	const listenLyricIndex = () => {
		clearInterval(timerCount[0])
		clearInterval(timerCount[2])
		timerCount[0] = setInterval(() => {
			if (lyrics[currentIndex.value] && bgm.currentTime > lyrics[currentIndex.value].time) currentIndex
				.value++
			console.log('$')
			// console.log(bgm.currentTime,currentIndex.value)
		}, 333)
		timerCount[2] = setInterval(()=>{
			rotateAngle.value = (rotateAngle.value + 1)%1440
			// console.log(rotateAngle.value)
		},16)
	}
	
	// onUnload(() => {
	// 	timerCount.forEach(item => {
	// 		clearInterval(item)
	// 	})
	// })
	
	onUnmounted(() => {
		timerCount.forEach(item => {
			clearInterval(item)
		})
	})

	function secToTime(seconds) {
		if (seconds === undefined) return "00:00"
		let hour = Math.floor(seconds / 3600)
		let minute = Math.floor(seconds / 60) % 60
		let second = Math.floor(seconds % 60)
		let str = ""
		if (hour === 0) {} else if (hour < 10) str += '0' + hour + ":"
		else str += hour + ":"
		if (minute === 0) str += '00:'
		else if (minute < 10) str += '0' + minute + ":"
		else str += minute + ":"
		if (second === 0) str += '00'
		else if (second < 10) str += '0' + second
		else str += second
		return str
	}

	function changeTime(e) {
		bgm.seek(e.detail.value)
		for (let i = 0; i < lyrics.length; i++) {
			if (e.detail.value < lyrics[i].time) {
				currentIndex.value = i
				break
			}
		}
		bgm.play()
		listenLyricIndex()
		isPlay.value = false
	}

	function listenSlider() {
		clearInterval(timerCount[1])
		timerCount[1] = setInterval(() => {
			nowTime.value = bgm.currentTime
			console.log('@')
		}, 1000)
	}

	function playModeUrl() {
		switch (playMode.value) {
			case 0:
				return "/static/24gl-repeat2.png" //循环播放
			case 1:
				return "/static/24gl-shuffle.png" //随机播放
			case 2:
				return "/static/24gl-repeatOnce2.png" //单曲循环
			case 3:
				return "/static/orderPlay.png" //顺序播放
		}
	}

	function playModeStr() {
		switch (playMode.value) {
			case 0:
				return "循环播放"
			case 1:
				return "随机播放"
			case 2:
				return "单曲循环"
			case 3:
				return "顺序播放"
		}
	}

	function changePlayMode() {
		getApp().globalData.playMode += 1
		getApp().globalData.playMode %= 4
		playMode.value = getApp().globalData.playMode
		// console.log(playMode.value,playModeStr())
		uni.showToast({
			title: `当前播放模式：${playModeStr()}`,
			icon: 'none',
			duration: 2000,
		})
	}

	function nextSong() {
		let playList = getApp().globalData.playList
		let l = playList.length
		let currentPlayIndex = getApp().globalData.currentPlayIndex
		// console.log(playList, l, currentPlayIndex)
		if (playMode.value === 0) {
			if (l === 1) bgm.seek(0)
			else {
				if (currentPlayIndex === l - 1) getApp().globalData.currentPlayIndex = 0
				else getApp().globalData.currentPlayIndex = currentPlayIndex + 1
			}
		} else if (playMode.value === 1) {
			if (l === 1) {
				bgm.seek(0)
			} else {
				let random = Math.floor(Math.random() * l)
				while (random == currentPlayIndex) {
					random = Math.floor(Math.random() * l)
				}
				getApp().globalData.currentPlayIndex = random
			}
		} else if (playMode.value === 2) {
			getApp().globalData.currentPlayIndex = currentPlayIndex + 1
		} else if (playMode.value === 3) {
			if (currentPlayIndex != l - 1) {
				getApp().globalData.currentPlayIndex = currentPlayIndex + 1
			}
		}
		// console.log(getApp().globalData.currentPlayIndex)
		if (currentPlayIndex != getApp().globalData.currentPlayIndex) {
			init()
		}
	}

	let showPlayList = ref(false)

	function playListShow() {
		showPlayList.value = !showPlayList.value
		// if(playlist.style.right==="0vw"){
		//     playlist.style.right="-50vw"
		//     playlist.style.opacity="0"
		// }else{
		//     playlist.style.right="0vw"
		//     playlist.style.opacity="1"
		// }
	}

	function listLength() {
		return getApp().globalData.playList.length
	}

	function listCurrent() {
		return getApp().globalData.currentPlayIndex
	}
</script>

<style lang="less">
	.box {
		position: absolute;
		display: flex;
	}

	.other {
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 2vh;
	}

	.shader {
		position: absolute;
		width: 100vw;
		height: 100vh;
		background: rgba(0, 0, 0, 0.5);
		-webkit-backdrop-filter: blur(25px);
		backdrop-filter: blur(25px);
		z-index: -1;
	}

	.bg {
		position: absolute;
		width: 100vw;
		height: 100vh;
		z-index: -2;
	}

	.title {
		color: #ededed;
		z-index: 1;
		line-height: 8vh;
		font-size: 1.5em;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	@keyframes imgRotate {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.album {
		width: 45vw;
		height: 45vw;
		border-radius: 50%;
		border: solid 8vh #111111;
		box-shadow: 0 0 2vh 2vh rgba(0, 0, 0, 0.5);
		margin: 3vh 0;
	}

	.lyrics {
		// margin: 2vh 0;
		height: 18vh;
		overflow: hidden;
	}

	.lyricsWrap {
		display: flex;
		flex-direction: column;
		transition: 0.333s;
	}

	.lyricsItem {
		color: #999;
		font-size: 0.8em;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 6vh;
	}

	.active {
		color: #fff;
	}

	.footer {
		display: flex;
		width: 80vw;
		justify-content: space-around;
		align-items: center;

		image {
			width: 15vw;
			height: 15vw;
		}
	}

	.progressBar {
		color: #fff;
		display: flex;
		justify-content: space-around;
		align-items: center;
		width: 100%;
	}

	.playList {
		display: flex;
		flex-direction: column;
		position: absolute;
		top: 0;
		z-index: 999;
		width: 80vw;
		height: 70%;
		background: rgba(0, 0, 0, 0.7);
		transition: all 0.7s ease 0ms;
		color: #fff;
		overflow: hidden;
		padding: 10vw;

		.scv {
			display: flex;
			flex-direction: column;
			height: 80%;
			width: 100%;
		}

		.listItem {
			display: flex;
			justify-content: space-around;
			align-items: center;
			padding: 2vh;

			text {
				font-size: 0.8em;
				line-height: 4vh;
				text-overflow: ellipsis;
				white-space: nowrap;
				overflow: hidden;
			}

			.listArtist {
				color: #ccc;
			}
		}

		.listText {
			display: flex;
			width: 80%;
			flex-direction: column;
		}

		.listItem:hover {
			background: rgba(255, 255, 255, 0.5);
		}
	}

	.listActive {
		background: rgba(255, 255, 255, 0.5);
	}

	.artist {
		color: #999;
		font-size: 0.8em;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 80%;
		text-align: center;
	}
</style>
